//
//  URL+SGExtension.swift
//  QingLiuSwift
//
//  Created by xyanl on 2024/12/12.
//  Copyright © 2024 考拉🐨. All rights reserved.
//

import UIKit

extension URL: SpadgerCompatible {}

// MARK: - 基本的扩展方法
public extension Spadger where Base == URL {
    
    /// 提取链接中的参数以字典形式显示
    /// let url = "http://zentao.dylan-saas.com/index.php?m=bug&f=browse&productid=1&branch=all&browseType=assigntome"
    /// 结果：["productid": "1", "browseType": "assigntome", "branch": "all", "m": "bug", "f": "browse"]
    var queryParameters: [String: String]? {
        guard let components = URLComponents(url: self.base, resolvingAgainstBaseURL: true),
              let queryItems = components.queryItems else {
            return nil
        }
        
        var parameters = [String: String]()
        for item in queryItems {
            parameters[item.name] = item.value
        }
        
        return parameters.isEmpty ? nil : parameters
    }
    
    /// 从url中获取后缀 例：mp3/mp4等等
    var pathExtension: String {
        return self.base.pathExtension.isEmpty ? "" : "\(self.base.pathExtension)"
    }
    
    /// 检测应用是否能打开这个URL
    var isCanOpenURL: Bool {
        UIApplication.shared.canOpenURL(self.base)
    }
    
    /// 属性说明
    func propertyDescription() {
        
        let dic: [String: Any] = [
            "absoluteString 完整的url字符串": base.absoluteString,
            "scheme 协议": base.scheme ?? "",
            "host 域名": base.host ?? "",
            "path 路径": base.path,
            "relativePath 相对路径": base.relativePath,
            "port 端口": base.port ?? 0,
            "pathComponents": base.pathComponents,
            "query 参数": base.query ?? ""
        ]
        
        print(dic as NSDictionary)
        
//        print("完整的url字符串 absoluteString：\(base.absoluteString)", "协议 scheme：\(base.scheme ?? "")", "域名 host：\(base.host ?? "")", "路径 path：\(base.path)", "相对路径 relativePath：\(base.relativePath)", "端口 port：\(base.port ?? 0)", "pathComponents：\(base.pathComponents)", "参数 query：\(base.query ?? "")")
    }
    
}
